package com.zxgllhh.service;

import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.io.FileUtils;

import com.zxgllhh.domain.Field;
import com.zxgllhh.domain.Table;
import com.zxgllhh.run.TableConnectionThread;
import com.zxgllhh.utils.PropertyUtils;
/**
 * 
 * @author Zhao,XingGuo
 *
 */
public class TableManager {

	public static List<String> getAllTableNames(Connection connection) throws Exception {
		List<String> allTables = new ArrayList<String>();
		DatabaseMetaData meta = connection.getMetaData();
		ResultSet rs = meta.getTables(null, PropertyUtils.getProperty("jdbc.username").toUpperCase(), null, new String[] { "TABLE" });
		while (rs.next()) {
			String tableName = rs.getString("TABLE_NAME");
			if (tableName.indexOf("$") > 0 || tableName.indexOf("0") > 0) {
				continue;
			}
			allTables.add(tableName);
		}
		rs.close();
		return allTables;
	}

	public static List<Table> getTableList(Connection connection, List<String> allTables) throws Exception {
		long time = System.currentTimeMillis();
		String projectName = PropertyUtils.getProperty("projectName");
		String companyName = PropertyUtils.getProperty("companyName");
		ExecutorService exec = Executors.newFixedThreadPool(10);
		int j = 0;
		int avg = allTables.size()/40+1;
		for(int i = 0 ; i < avg ; i++ ){
			List<String> subTableList = null;
			if(allTables.size() < j+40){
				subTableList = allTables.subList(j, allTables.size());
			}else{
				subTableList = allTables.subList(j, j+40);
			}
			j = j+40;
			
			TableConnectionThread run = new TableConnectionThread();
			run.setTableList(subTableList);
			exec.execute(run);
		}
		exec.shutdown();
		
		File file = new File("E://generatorCode");
		FileUtils.deleteDirectory(file);
		FileUtils.forceMkdir(new File("E://generatorCode/src/com/"+companyName+"/" + projectName + "/web/struts/manager/admin"));
		FileUtils.forceMkdir(new File("E://generatorCode/src/com/"+companyName+"/" + projectName + "/domain"));
		FileUtils.forceMkdir(new File("E://generatorCode/src/com/"+companyName+"/" + projectName + "/service/impl"));
		FileUtils.forceMkdir(new File("E://generatorCode/src/com/"+companyName+"/" + projectName + "/dao/ibatis/maps"));
		FileUtils.forceMkdir(new File("E://generatorCode/WebContent/admin/"));
		
		while (!exec.isTerminated()){
		}
		
		System.out.println("all database : " + (System.currentTimeMillis() - time) + " milliseconds");
		
		return com.zxgllhh.domain.ConnectionContext.getTableList();
		
	}

	public List<Field> getFieldListByTableName(Connection connection, String tableName) throws Exception {
		List<Field> fieldList = new ArrayList<Field>();
		DatabaseMetaData meta = connection.getMetaData();
		ResultSet rs = null;
		rs = meta.getColumns(null, PropertyUtils.getProperty("jdbc.username").toUpperCase(), tableName, null);
		while (rs.next()) {
			Field field = new Field();
			// 列名称
			String culumnName = rs.getString("COLUMN_NAME");
			//小数部分的位数。对于 DECIMAL_DIGITS 不适用的数据类型，则返回 0。 
			int decimal_digits = rs.getInt("DECIMAL_DIGITS");
			// 来自 java.sql.Types 的 SQL 类型
			int datatype = rs.getInt("DATA_TYPE");
			// 列的大小。
			int size = rs.getInt("COLUMN_SIZE");
			// 是否允许使用 NULL。
			int nullable = rs.getInt("NULLABLE");
			if (nullable == DatabaseMetaData.columnNullable) {
				field.setNullable(true);
			} else {
				field.setNullable(false);
			}
			//描述列的注释（可为 null）
			String remarks = rs.getString("REMARKS");
			field.setRemarks(remarks);
			field.setCulumnName(culumnName);
			field.setSize(String.valueOf(size));
			field.setDatatype(String.valueOf(datatype));
			field.setDecimal_digits(decimal_digits);
			fieldList.add(field);
		}
		rs.close();
		return fieldList;
	}

	public List<String> getPrimaryKeyListByTableName(Connection connection, String tableName) throws Exception {

		List<String> primaryKeyList = new ArrayList<String>();
		DatabaseMetaData meta = connection.getMetaData();
		ResultSet rs = null;
		rs = meta.getPrimaryKeys(null, tableName, tableName);

		while (rs.next()) {
			String culumnName = rs.getString("COLUMN_NAME");
			primaryKeyList.add(culumnName);
		}
		rs.close();
		return primaryKeyList;
	}
}
